import type { AsyncDataResult, AsyncVoid } from '../define/types'
import type IUsed from '../define/used'
import knex from '../connection'
import Entity from './entity'

class Used implements IUsed {
  async get(table: string): AsyncDataResult<number> {
    const result = await knex(table)
      .count('* as total')
      .sum({ usedCount: knex.raw('CASE WHEN used = 1 THEN 1 ELSE 0 END') })
    const total: any = result[0].total
    const usedCount = result[0].usedCount
    const usageRate = (usedCount / total) * 100
    return parseInt(String(usageRate))
  }
  async use(table: string, id: string): AsyncVoid {
    const entity = new Entity(table)
    await entity.update({ id, used: 1 })
  }
  
}

export default new Used()
